<!DOCTYPE html>
<script src="../include.js"></script>
<script>
    const COOKIE_NAME = "testcookie";

    async function hasCookie(resp) {
        const body = await resp.json();
        return body["Cookie"]?.find(
            (cookie) => cookie.trim().startsWith(COOKIE_NAME + '=')
        );
    }

    promiseTest(async () => {
        try {
            const httpServer = httpTestServer();
            const url = await httpServer.createEcho("GET", `/fetch-cors-credentials-flag-cookie`, {
                status: 200,
                headers: {
                    "Access-Control-Allow-Origin": location.origin,
                    "Access-Control-Allow-Credentials": "true",
                    "Set-Cookie": `${COOKIE_NAME}=COOKIE`
                },
                reflect_headers_in_body: true,
            });

            let resp = await fetch(url, { credentials: 'omit' });
            if (await hasCookie(resp)) {
                println("FAIL - cookie was set");
                return;
            }

            resp = await fetch(url, { credentials: 'include' });
            if (await hasCookie(resp)) {
                println("FAIL - cookie was set");
                return;
            }

            resp = await fetch(url, { credentials: 'include' });
            if (!await hasCookie(resp)) {
                println("FAIL - cookie was not set");
                return;
            }

            println("PASS");
        } catch (err) {
            println("FAIL - " + err);
        }
    });
</script>
